package com.gec.service.Impl;

import com.gec.dao.DeptDao;
import com.gec.domain.Dept;
import com.gec.domain.PageBean;
import com.gec.domain.PageParam;
import com.gec.service.abst.DeptService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.List;

@Service
public class DeptServiceImpl extends BaseService implements DeptService {

    private final DeptDao deptDao;

    public DeptServiceImpl(DeptDao deptDao) {
        this.deptDao = deptDao;
    }


    @Override
    public PageBean getAllDept(PageParam param) {
        int size = param.getLimit();  //页大小
        int page = param.getPage();   //页码
        //{1}在查询之前先调用这个方法来准备拦截查询
        Page<Object> pageInfo = PageHelper.startPage(page, size, true);
        //{2}调用 dao 方法来查询
        List<Dept> list = deptDao.getAllDept(param.getKeywords());
        PageBean pBean = new PageBean();
        int total = (int) pageInfo.getTotal();
        //{3}生成 PageBean, 再封装信息到 pBean
        pBean.setCount(total);  //总记录数
        pBean.setData(list);    //用户列表
        pBean.setCode(0);     //状态码
        return pBean;
    }


    @Override
    public void saveDept(Dept dept) {
        String id = dept.getId();
        if (id == null) {
            String pids = dept.getPids() + "," + dept.getParentId();
            dept.setId(uuid());
            dept.setPids(pids);
            deptDao.addDept(dept);
        } else {
            deptDao.updateDept(dept);
        }
    }


    @Override
    public Dept getDeptById(String id) {
        Dept dept = deptDao.getDeptById(id);
        return dept;
    }

    @Override
    public void deleteDept(String id) throws SQLException {
        int count = deptDao.findDeptCount(id);
        if (count==0) {
            deptDao.delDept(id);
        }else{
            throw new SQLException("存在子部门，无法删除");
        }
    }
}
